package fr.orleans.tournament;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import entities.Tournament;
import enums.TournamentStatus;
import fr.orleans.tools.JSFServices;
import fr.orleans.tools.ManagedBeans;

@ManagedBean
@ViewScoped
public class TournamentList extends ManagedBeans {

	private List<Tournament> listTournament;
	private HashMap<Tournament, Integer> teambyTournament;

	private Tournament tournament;
	private String startDateString;

	public List<Tournament> getListTournament() {
		if(this.listTournament == null)
			this.listTournament = this.getService().getWebAction().getListTournamentByFlagActivated();

		for(Tournament tour : this.listTournament)
			this.getTeambyTournament().put(tour, (int) this.getService().getWebAction().getCountTeamByTournamentByFlagActivated(tour));

		return listTournament;
	}

	public void setListTournament(List<Tournament> listTournament) {
		this.listTournament = listTournament;
	}

	public HashMap<Tournament, Integer> getTeambyTournament() {
		if(this.teambyTournament == null)
			this.teambyTournament = new HashMap<>();
			return teambyTournament;
	}

	public void setTeambyTournament(HashMap<Tournament, Integer> teambyTournament) {
		this.teambyTournament = teambyTournament;
	}


	public Tournament getTournament() {
		if(this.tournament == null)
			this.tournament = new Tournament();
		return tournament;
	}

	public void setTournament(Tournament tournament) {
		this.tournament = tournament;
	}

	public String getStartDateString() {
		return startDateString;
	}

	public void setStartDateString(String startDateString) {
		this.startDateString = startDateString;
	}

	public String addTournament(){
		try {
			tournament.setStartDate(new SimpleDateFormat("yyyy-MM-dd").parse(this.startDateString));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		tournament.setStatus(TournamentStatus.preparation);
		this.getService().getWebAction().createTournament(tournament);
		return "/modules/tournament/adminList.xhtml";
	}

	public String editTournament(Tournament oneTournament){
		JSFServices.putParameterInRequestMap("tournament", oneTournament);
		return "/modules/tournament/adminEdit.xhtml";
	}
	
	public String viewTournament(Tournament oneTournament){
		JSFServices.putParameterInRequestMap("tournament", oneTournament);
		return "/modules/tournament/adminView.xhtml";
	}

	public String deleteTournament(Tournament oneTournament){
		this.getService().getWebAction().removeTournament(oneTournament);
		return "/modules/tournament/adminList.xhtml";
	}
}